import * as vscode from "vscode"
import Utils from "./utils";
import * as yaml from "js-yaml"
import * as fs from "fs"
import { pinyin } from "pinyin-pro"

export default class GlobalData {
    private static instance: GlobalData

    private variables: any = null

    private completionItems: any = {}
    private constructor() {

    }

    private genCompletionItem(keys: string[]): vscode.CompletionItem[] {
        return keys.map(key => {
            const item = new vscode.CompletionItem(key + " | " + pinyin(key, { pattern: "initial" }), vscode.CompletionItemKind.Value)
            item.insertText = key
            return item
        })
    }


    public loadVar() {
        const projectPath = Utils.getProjectPath();
        this.variables = yaml.load(fs.readFileSync(`${projectPath}/docs/variables.yaml`, "utf8")) as object;
        // 处理其他情况赋值
        this.genCompleteItems();
    }



    private genCompleteItems() {
        // 解析key
        // 一级解析
        let firstkeys = Object.keys(this.variables);
        this.completionItems["_root"] = this.genCompletionItem(firstkeys);
        // 二级解析
        firstkeys.forEach(key => {
            const keys = Object.keys(this.variables[key]);
            this.completionItems[key] = this.genCompletionItem(keys);
        });
    }

    VariaablesKeys(document?: vscode.TextDocument): object {
        return this.completionItems
    }

    public static Instance(): GlobalData {
        if (!GlobalData.instance) {
            GlobalData.instance = new GlobalData()
        }
        return GlobalData.instance
    }
}